<template>
     <div class="container">
            <el-form :inline="true" :model="searchInfo" ref="searchInfo">
                <el-form-item label="应用名称">
                    <el-input
                            v-model="searchInfo.apps_name"
                            placeholder="请输入数据库名称"
                            clearable
                            disabled
                    />
                </el-form-item>
                <el-form-item label="Jenkins-job名称" prop="apps_job_name">
                    <el-input
                            v-model="searchInfo.apps_job_name"
                            placeholder="请输入Jenkins Job名称"
                            clearable
                    />
                </el-form-item>
                <el-form-item label="环境名称" prop="deploy_env">
                    <el-select clearable  placeholder="请选择" v-model="searchInfo.deploy_env" style="width:100%">
                        <el-option
                                v-for="dict in EnvOptions"
                                :key="dict.item_value"
                                :label="dict.item_name"
                                :value="dict.item_value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button
                            class="filter-item"
                            type="primary"
                            icon="el-icon-search"
                            @click="handleQuery"
                    >搜索</el-button>
                </el-form-item>
            </el-form>
            <el-form>
                <el-form-item>
                  <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="createDeployAppConfigure()">新增</el-button>
                </el-form-item>
            </el-form>
            <el-table
                    :data="tableData"
                    row-key="ID"
                    border
                    ref="multipleTable"
                    tooltip-effect="dark"
                    style="width: 100%">
                <el-table-column label="ID" width="50" align="center" prop="ID">
                    <template slot-scope="scope">{{scope.row.ID}}</template>
                </el-table-column>
                <el-table-column prop="apps_name" label="应用名称"/>
                <el-table-column prop="apps_job_name" label="Job名称"/>
                <el-table-column prop="apps_port" label="应用端口" v-if="!isCommon" />
                <el-table-column prop="apps_type" label="应用类型"/>
                <el-table-column prop="projects.project_fullname" label="项目名称"/>
                <el-table-column prop="deploy_env" label="环境名称">
                    <template slot-scope="scope">{{scope.row.deploy_env | basecode(scope.row.deploy_env,'env_name')}}</template>
                </el-table-column>
                <el-table-column prop="deploy_status" label="状态" :render-header="renderHeadeStatus">
                    <template slot-scope="scope">{{scope.row.deploy_status | basecode(scope.row.deploy_status,'deploy_status')}}</template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="350">
                    <template slot-scope="scope">
                        <el-button class="filter-item" type="success" icon="el-icon-copy-document"  @click="copyDeployApplyConfigure(scope.row)">拷贝</el-button>
                        <el-button @click="updateDeployApplyConfigure(scope.row)" icon="el-icon-edit" size="small" type="primary">编辑</el-button>
                        <el-button @click="DeployApplyConfigureJenkins(scope.row)" :disabled="scope.row.deploy_status == 1 || scope.row.deploy_status == 3" icon="el-icon-check" size="small" type="warning">Jenkins</el-button>
                        <el-button @click="deleteDeployAppConfigure(scope.row)" type="danger" icon="el-icon-delete" style="margin-left: 6px;" size="mini" >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    :current-page="page"
                    :page-size="pageSize"
                    :page-sizes="[10, 30, 50, 100]"
                    :style="{float:'right',padding:'20px'}"
                    :total="total"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    layout="total, sizes, prev, pager, next, jumper"
            ></el-pagination>
            <el-dialog :title="dialogTitle"  :close-on-click-modal="false" :visible.sync="dialogFormVisible" width="1000px"  @close="closeDialog">
                <el-form ref="appsForm" :model="formData" :rules="rules" size="medium" label-width="120px">
                    <el-row :gutter="10">
                      <el-col :span="20" :offset="2">
                        <el-col :span="12">
                            <el-form-item label="应用名称" prop="apps_name">
                                <el-input
                                        v-model="formData.apps_name"
                                        prefix-icon="el-icon-info"
                                        placeholder="请输入应用名称"
                                        clearable
                                        disabled
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                              <el-form-item label="部署环境" prop="deploy_env" >
                                  <el-select  @change="FillAppsCode" placeholder="请选择" :disabled="type=='update'"  v-model="formData.deploy_env" style="width:100%">
                                      <el-option
                                              v-for="dict in EnvOptions"
                                              :key="dict.item_value"
                                              :label="dict.item_name"
                                              :value="dict.item_value"
                                      ></el-option>
                                  </el-select>
                              </el-form-item>
                          </el-col>
                        <el-col :span="12">
                            <el-form-item label="jenkins-job名称" prop="apps_job_name">
                                <el-input
                                        v-model.trim="formData.apps_job_name"
                                        prefix-icon="el-icon-info"
                                        :disabled="true"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="分支名称" prop="branch_name">
                              <el-input v-model.trim="formData.branch_name" placeholder="请输入分支名称" prefix-icon="el-icon-info" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                              <el-form-item label="应用包名称" prop="package_name">
                                  <el-input
                                          v-model.trim="formData.package_name"
                                          prefix-icon="el-icon-info"
                                          placeholder="请输入应用包名称"
                                          clearable
                                  ></el-input>
                              </el-form-item>
                          </el-col>
                        <el-col :span="12" v-if="!isCommon">
                            <el-form-item label="应用端口" prop="apps_port">
                              <el-input v-model.trim="formData.apps_port" prefix-icon="el-icon-info"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="项目名称" prop="project_code" required>
                                <el-input
                                        v-model="formData.project_code"
                                        prefix-icon="el-icon-info"
                                        placeholder="请输入项目名称"
                                        clearable
                                        disabled
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="!isCommon">
                            <el-form-item label="健康检查" prop="health_check">
                                <el-input v-model.trim="formData.health_check" prefix-icon="el-icon-info" :disabled="formData.apps_type == 'web'" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="应用类型" prop="apps_type">
                                <el-input
                                        v-model="formData.apps_type"
                                        prefix-icon="el-icon-info"
                                        placeholder="请输入应用类型"
                                        clearable
                                        disabled
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="!isCommon">
                            <el-form-item label="部署路径" prop="deploy_path">
                               <el-input v-model.trim="formData.deploy_path" placeholder="/app/xxxx" prefix-icon="el-icon-info"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="编译产出路径" prop="build_path">
                               <el-input v-model.trim="formData.build_path" prefix-icon="el-icon-info"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="编译命令" prop="build_run">
                                <el-input v-model="formData.build_run" placeholder="前端npm/后端mvn的编译命名" clearable type="textarea" ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="!isCommon">
                            <el-form-item label="部署命令" prop="deploy_run">
                                <el-input v-model="formData.deploy_run" placeholder="输入部署命令: 后端是部署命令 前端是reload nginx命令" clearable type="textarea"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" >
                            <el-form-item label="机房" prop="server_idc" >
                              <el-select  placeholder="请选择" v-model="formData.server_idc"  style="width:90%">
                                    <el-option
                                            v-for="dict in IdcOptions"
                                            :key="dict.item_value"
                                            :label="dict.item_name"
                                            :value="dict.item_value"
                                    ></el-option>
                              </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12" >
                          <div  style="color: red;margin-top: 11px">(重要提醒:此处机房不要选错，一旦创建无法更新！)</div>
                        </el-col>
                        <el-col :span="24" v-if="!isCommon">
                            <el-form-item label="服务器选择">
                              <el-transfer
                                      v-model="VirtualValue"
                                      :props="{
                                          key: 'value',
                                          label: 'desc'
                                        }"
                                      :right-default-checked="VirtualValue"
                                      :button-texts="['左边', '右边']"
                                      :titles="['项目服务器', '使用服务器']"
                                      :data="VirtualData"
                              >
                              </el-transfer>
                            </el-form-item>
                          </el-col>
                      </el-col>
                    </el-row>
                </el-form>
                <div class="dialog-footer" slot="footer">
                    <el-button @click="closeDialog">取 消</el-button>
                    <el-button @click="enterDialog" type="primary">确 定</el-button>
                </div>
            </el-dialog>
            <el-dialog :title="dialogCopyTitle"  :close-on-click-modal="false" :visible.sync="dialogCopyFormVisible" width="600px"  @close="closeCopyDialog">
             <el-form ref="appsCopyForm" :model="copyFormData" :rules="rules" size="medium" label-width="120px">
                 <el-row :gutter="10">
                     <el-col :span="20" :offset="2">
                         <el-col :span="24">
                             <el-form-item label="应用ID" prop="id">
                                 <el-input v-model="copyFormData.id" prefix-icon="el-icon-info" placeholder="请输入应用ID" clearable disabled></el-input>
                             </el-form-item>
                         </el-col>
                         <el-col :span="24">
                             <el-form-item label="部署环境" prop="deploy_env">
                                 <el-select  @change="FillAppsCode" placeholder="请选择"  v-model="copyFormData.deploy_env" style="width:100%">
                                     <el-option
                                             v-for="dict in EnvOptions"
                                             :key="dict.item_value"
                                             :label="dict.item_name"
                                             :value="dict.item_value"

                                     ></el-option>
                                 </el-select>
                             </el-form-item>
                         </el-col>
                     </el-col>
                 </el-row>
             </el-form>
             <div class="dialog-footer" slot="footer">
                 <el-button @click="closeCopyDialog">取 消</el-button>
                 <el-button @click="enterCopyDialog" type="primary">确 定</el-button>
             </div>
         </el-dialog>
        </div>
</template>

<script>
    import {
        getAppConfigureList,
        updateAppConfigure,
        createAppConfigure,
        deleteAppConfigure,
        copyAppConfigure,
    } from "@/api/deploy_configure";
    import { getServerList }  from "@/api/cmdb_server";
    import infoList from '@/mixins/infoList'
    import {createDeployAppJenkins,updateDeployAppJenkins} from'@/api/deploy_jenkins';
    export default {
        name: "configure",
        mixins: [infoList],
        data() {
            return {
                tableData:[],
                VirtualData: [],
                VirtualValueData: [],
                VirtualValue: [],
                transferDate: [],
                ProjectOptions: [],
                EnvOptions: [],
                IdcOptions:[],
                AppsTypeOptions: [],
                // 非单个禁用
                single: true,
                multipleSelection: [],
                dialogFormVisible: false,
                dialogCopyFormVisible:false,
                dialogCopyTitle:"拷贝配置",
                type:"",
                dialogTitle: "新增配置",
                listApi: getAppConfigureList,
                searchInfo: {
                    apps_name: null,
                    project_code: null,
                    deploy_env: null
                },
                copyFormData:{
                    id:undefined,
                    deploy_env: null,
                },
                formData: {
                    apps_name: null,
                    branch_name: null,
                    apps_job_name:null,
                    package_name:null,
                    apps_port: null,
                    project_code: null,
                    health_check: 'nohealthpage',
                    deploy_env: null,
                    apps_type: null,
                    deploy_path: null,
                    build_path: null,
                    backup_path: null,
                    build_run: null,
                    deploy_run: null,
                    server_idc:null,
                    virtualCodeInfos: []
                },
                rules: {
                    apps_name: [{ required: true, message: "请输入应用名称", trigger: "blur"}],
                    package_name: [{ required: true, message: "请输入应用包名称", trigger: "blur"}],
                    // apps_port: [{ required: true, message: '请正确输入端口',validator: isPort,trigger: 'blur' }],
                    gitlab_url: [{ required: true, type: 'url', message: '输入合法的链接', trigger: 'blur' }],
                    branch_name: [{ required: true, message: "请输入分支名称", trigger: "blur"}],
                    project_code: [{ required: true, message: "请选择项目", trigger: "blur"}],
                    deploy_env: [{ required: true, message: "请选择部署环境", trigger: "blur"}],
                    apps_type: [{ required: true, message: "请选择应用类型", trigger: "blur"}],
                    // deploy_path: [{ required: true, message: "请输入部署路径", trigger: "blur"}],
                    build_path: [{ required: true, message: "请输入应用编译路径", trigger: "blur"}],
                    build_run: [{ required: true, message: "请输入编译命令", trigger: "blur"}],
                    // deploy_run: [{ required: true, message: "请输入部署内容", trigger: "blur"}],
                    // server_idc:[{ required: true, message: "请选择部署机房", trigger: "blur"}]
                },
                isCommon:false

            }
        },
        async created() {
            await this.getSearch(this.$route.query.appsName)
            this.formData.apps_name = this.$route.query.appsName
            this.formData.project_code = this.$route.query.projectCode
            this.formData.apps_type = this.$route.query.appsType
            if (this.formData.apps_type === "common" || this.formData.apps_type === "apk"){
                this.isCommon = true
            }
            await this.getEnvData();
            await this.getIdcData();
        },
        methods: {
            //页面加载
            async getSearch(params){
                this.searchInfo.apps_name = params
                await this.getTableData();
            },
            //拷贝
            async copyDeployApplyConfigure(row){
                this.dialogTitle = '拷贝配置'
                this.type = "copy";
                this.copyFormData.id = row.ID
                this.dialogCopyFormVisible = true;
            },
            async DeployApplyConfigureJenkins(row){
                if (row.deploy_status == 0 ) {
                    const res = await createDeployAppJenkins({ 'Id':row.ID});
                    if (res.code == 0) {
                        this.$message({
                            type: "success",
                            message: "创建JOB成功!"
                        });
                        await this.getTableData();
                    }
                } else {
                    const res = await updateDeployAppJenkins({ 'Id':row.ID});
                    if (res.code == 0) {
                        this.$message({
                            type: "success",
                            message: "更新JOB成功!"
                        });
                        await this.getTableData();
                    }
                }
            },
            async getEnvData() {
                this.EnvOptions = this.getDicItemList('env_name')
            },
            async getIdcData(){
                this.IdcOptions = this.getDicItemList('server_idc')
            },
            // 项目搜索
            handleQuery() {
                this.getTableData()
            },
            //回填apps_code
            FillAppsCode() {
                this.formData.apps_job_name = this.formData.deploy_env + "-" +this.formData.apps_name
            },
            async updateDeployApplyConfigure(row) {
                this.dialogTitle = '编辑配置'
                this.type = "update";
                this.formData = row
                this.dialogFormVisible = true;
                this.AppsTypeOptions = this.getDicItemList('apps_type')
                if (this.formData.apps_type === "common" || this.formData.apps_type === "apk"){
                    this.isCommon = true
                }else {
                    this.VirtualData=[];
                    getServerList({'page':1, 'pageSize': 60, 'status':'1' ,'project_code': this.formData.project_code}).then(response => {
                        let list=response.data.list;
                        for (let i = 0;i < list.length;i++){
                            this.VirtualData.push({
                                value : list[i].virtual_code,
                                desc: list[i].ip_address,
                            })
                        }
                    })
                    let arr = []
                    this.VirtualValue = []
                    row.DeployAppVirtual.map((item) => {
                        arr.push(item.virtual_code)
                    })
                    this.VirtualValue = arr
                }
            },
            closeDialog(bool) {
                bool && this.getTableData()
                this.$refs['appsForm'].resetFields()
                this.dialogFormVisible = false
            },
            closeCopyDialog(bool) {
                bool && this.getTableData()
                this.$refs['appsCopyForm'].resetFields()
                this.dialogCopyFormVisible = false
            },
            deleteDeployAppConfigure(row) {
                this.$confirm("此操作将永久删除该应用, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(async () => {
                        this.visible = false;
                        const res = await deleteAppConfigure({ ID: row.ID });
                        if (res.code == 0) {
                            this.$message({
                                type: "success",
                                message: "删除成功!"
                            });
                            await this.getTableData();
                        }
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除"
                        });
                    });
            },
            async enterDialog() {
                this.$refs['appsForm'].validate(async valid => {
                    if (!valid) return
                    let res;
                    this.transferDate = []
                    for (let i = 0;i < this.VirtualValue.length;i++){
                        this.transferDate.push({
                            virtual_code : this.VirtualValue[i],
                        })
                    }
                    this.formData.virtualCodeInfos = this.transferDate
                    switch (this.type) {
                        case "create":
                            res = await createAppConfigure(this.formData);
                            this.closeDialog(true)
                            break;
                        case "update":
                            res = await updateAppConfigure(this.formData);
                            this.closeDialog(true)
                            break;
                        default:
                            res = await createAppConfigure(this.formData);
                            this.closeDialog(true)
                            break;
                    }
                    if (res.code == 0) {
                        this.$message({
                            type:"success",
                            message:"创建/更改成功"
                        })
                        this.closeDialog(true);
                        await this.getTableData();
                    }
                })

            },
            async enterCopyDialog() {
                this.$refs['appsCopyForm'].validate(async valid => {
                    if (!valid) return
                    let res;
                    switch (this.type) {
                        case "copy":
                            res = await copyAppConfigure(this.copyFormData);
                            this.closeCopyDialog(true)
                            break;
                        default:
                            res = await copyAppConfigure(this.copyFormData);
                            this.closeCopyDialog(true)
                            break;
                    }
                    if (res.code == 0) {
                        this.$message({
                            type:"success",
                            message:"拷贝成功"
                        })
                        this.closeCopyDialog(true);
                        await this.getTableData();
                    }
                })

            },
            async createDeployAppConfigure(){
                this.dialogTitle = '新增应用配置'
                this.type = 'create';
                this.dialogFormVisible = true;
                this.AppsTypeOptions = this.getDicItemList('apps_type')
                this.VirtualData=[];
                this.VirtualValue=[];
                getServerList({'page':1, 'pageSize': 60,'status': '1', 'project_code': this.formData.project_code}).then(response => {
                    let list=response.data.list;
                      for (let i = 0;i < list.length;i++){
                         this.VirtualData.push({
                             value : list[i].virtual_code,
                             desc: list[i].ip_address,
                         })
                      }
                })
            },
            renderHeadeStatus (h, { column, $index }) {
              // h 是一个渲染函数       column 是一个对象表示当前列      $index 第几列
              console.log($index)
              return h("div", {
                style: {
                  paddingTop:'10px'
                },
              }, [
                h("span", column.label + "  ", {
                  // align: "center",
                  // marginTop: "-20px"
                }),
                h(
                  "el-popover",
                  {
                    props: {
                      placement: "top-start",    // 一般 icon 处可添加浮层说明，浮层位置等属性
                      // width: "100",
                      trigger: "hover"
                    }
                  },
                  [
                    h("p", "显示同步jenkins对应JOB的状态", {
                      // class: "text-align: center; margin: 0"
                    }),
                    h("i", {                            // 生成 i 标签 ，添加icon 设置 样式，slot 必填
                      class: "el-icon-question",
                      // style: "color:#ccc,margin:0px,padding-top:0px",
                      slot: "reference"
                    })
                  ]
                )
              ])
            }
          },


    }

</script>

<style scoped>
    .container{
    width: calc(100% - 70px);
    position: absolute;
    top: 0;right:  0;
    background: #fff;
    border-radius: 0px 4px 4px 0px;
    padding: 20px 20px 0;
    height: 100%;
  }
</style>
